package model

import (
	"errors"
	"fmt"
	"gadmin/conf"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func init() {
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
		conf.Conf.MySQL.User, conf.Conf.MySQL.Password, conf.Conf.MySQL.Host,
		conf.Conf.MySQL.Port, conf.Conf.MySQL.Database, conf.Conf.MySQL.Charset)

	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	DB.AutoMigrate(&Table{}, &Column{}, &Menu{}, &Datasource{}, &User{}, &Bookmark{},
		&Workflow{}, &WorkflowHistory{}, &StepHistory{})

	menus := []Menu{
		{ID: 1, Name: "workplace", Title: "工作台", Icon: "DashboardOutlined", Target: "_self", Path: "/workplace", Component: "@/pages/workplace", RenderMenu: true, Cacheable: true},
		{ID: 3, Name: "personal", Title: "个人中心", Icon: "ProfileOutlined", Path: "/personal", Component: "@/pages/personal", RenderMenu: true},
		{ID: 6, Name: "system", Title: "系统配置", Icon: "SettingOutlined", Target: "_self", Path: "/system", Component: "@/components/layout/BlankView.vue", RenderMenu: true, Cacheable: true},
		{ID: 8, Name: "menu", Title: "菜单管理", Target: "_self", Path: "/system/menu", Component: "@/pages/system", RenderMenu: true, Cacheable: true, Parent: "system"},
		{ID: 7, Name: "user", Title: "用户管理", Target: "_self", Path: "/config/dict", Component: "@/pages/dict", RenderMenu: true, Cacheable: true, Parent: "system"},
		// {ID: 9, Name: "bilibili", Title: "B站", Icon: "BoldOutlined", Badge: "iframe", Target: "_self", Path: "/bilibili", Component: "iframe", RenderMenu: true, Permission: "edit", Cacheable: true, Link: "https://www.bilibili.com"},
		// {ID: 10, Name: "github", Title: "Github", Icon: "GithubOutlined", Badge: "link", Target: "_blank", Path: "/github", Component: "link", RenderMenu: true, Cacheable: true, Link: "https://github.com/stepui/stepin-template"},
		{ID: 11, Name: "datasource", Title: "数据源", Target: "_self", Path: "/system/datasource", Component: "@/pages/datasource/Datasource.vue", Parent: "system", RenderMenu: true, Cacheable: true},
		{ID: 12, Name: "workflow", Title: "工作流", Target: "_self", Path: "/system/workflow", Component: "@/pages/workflow/Workflow.vue", Parent: "system", RenderMenu: true, Cacheable: true},
		{ID: 2, Name: "table", Title: "表格管理", Target: "_self", Path: "/system/table", Component: "@/pages/table", Parent: "system", RenderMenu: true, Cacheable: true},
	}

	users := []User{
		// sha512 888888
		{ID: 1, Username: "admin", Password: "e4aed93ec8e0084edaef0cb945aa5acb885792dea7c115f6de9a96c77df0ca617761738c76e965f18aafc30eccbe0dacc9ec1788a7a1bbc0d6ef59b98047c099"},
	}

	for _, menu := range menus {
		var _menu Menu
		result := DB.First(&_menu, menu.ID)
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			DB.Create(&menu)
		}
	}

	for _, user := range users {
		var _user User
		result := DB.First(&_user, user.ID)
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			DB.Create(&user)
		}
	}
}
